#!/usr/bin/env python
# -*- coding: utf-8 -*-

import paramiko  # 用于调用scp命令
from scp import SCPClient


from .utils import tools
from .utils import sqldb
from .utils import odoorpc
from .utils.control import Control

import time
import os
import logging  # 引入logging模块

logger = logging.getLogger()
# logger.info('set loggin ok')


def get_rpi_debug(conf_file):
    rpi_debug = conf_file['options'].get('rpi_debug')
    rpi_debug = rpi_debug and eval(rpi_debug)
    # logger.info('rpi_debug is: %s' % rpi_debug)
    return rpi_debug


def check_network(num0=None):
    import urllib.request
    url = "http://www.baidu.com"

    num = num0 or 4
    status = False
    while num and not status:
        num = num - 1
        # print('num,', num)
        try:
            status = urllib.request.urlopen(url)
            return status
        except:
            time.sleep(2)
            continue

    return status


def get_db(conf_file):
    options = conf_file.get('options')
    rpi_debug = get_rpi_debug(conf_file)

    # print('db options,', options)
    if rpi_debug:
        # logger.info('rpi_debug is %s, local db need not' % rpi_debug)
        return None

    local_db = options.get('local_db')
    db = sqldb.get_db(local_db)
    # logger.info('local db is ok, db file: %s' % local_db)
    return db


def get_odoo(conf_file, gatewate_code):
    options = conf_file.get('options')
    odoo = odoorpc.get_odoo(gatewate_code=gatewate_code,  **options)
    rpi_debug = get_rpi_debug(conf_file)
    if rpi_debug:
        pass
        # logger.info('rpi_debug is %s, odoo need not' % rpi_debug)
    else:
        pass
        # logger.info('connect odoo is ok, session_id=: %s' % odoo.session_id)
    return odoo


def get_port(conf_file):
    # 读配置文件
    # port = '/dev/ttyS0'  # 虚拟机的串口
    # port = '/dev/ttyAMA0'  # 树莓派的串口
    port = conf_file['options']['serial_port']
    # logger.info('serial port is: %s' % port)
    return port


def upload_log(gatewate_code):
    host = '106.13.191.63'
    port = 22
    username = 'root'
    password = 'root@szdw2020'

    remote_path = "/var/log/odoo/thewell"
    log_file = 'rpi_main.log'

    tt = time.time()
    tt = time.localtime(time.time())

    dt = tt.tm_year * 10000 + tt.tm_mon * 100 + tt.tm_mday
    tm = tt.tm_hour * 10000 + tt.tm_min * 100 + tt.tm_sec
    remote_file = '%s/%s_%s_%s.log' % (remote_path, gatewate_code, dt, tm)

    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
    ssh_client.connect(host, port, username, password)
    scpclient = SCPClient(ssh_client.get_transport(), socket_timeout=15.0)

    try:
        scpclient.put(log_file, remote_file)

    except FileNotFoundError as e:
        print(e)
        print("系统找不到指定文件" + log_file)
    else:
        print("文件上传成功")
    ssh_client.close()


def main_base():
    log_file = 'rpi_main.log'
    with open(log_file, "w", encoding="utf-8") as f2:
        f2.write("")

    conf_file = tools.get_config()
    # logger.info('cfg file: %s' % conf_file)
    # 设置 运行日志文件
    logging_level = conf_file['options'].get('logging_level') or 'INFO'
    tools.set_logging('rpi_main', logging_level)

    admin_debug = conf_file['options'].get('admin_debug')
    admin_debug = admin_debug and eval(admin_debug)
    # logger.info('admin_debug is: %s' % admin_debug)

    # rpi_debug = get_rpi_debug(conf_file)
    # logger.info('rpi_debug is: %s' % rpi_debug)

    # 1 初始化 设置. 串口号, 连接 本地数据库
    port = get_port(conf_file)
    db = get_db(conf_file)

    # 2 启动 主控线程, 接收 从机的应答
    # logger.info('init contorl')
    odoo = None
    ctrl = Control(dev=port, host='host', odoo=odoo,  db=db)
    # logger.info('init contorl ok')

    # 3 下发通知, 等待获取 gateway_code
    now_timestamp = 0
    gatewate_code = ctrl.send_ready(now_timestamp)
    # gatewate_code = ctrl.send_ready(now_timestamp)
    # return None

    if not gatewate_code:
        logger.info('slave no ack, quit and not shutdown')
        return None

    # 4 联网
    # logger.info('to check network')
    logger.info('sleep 100s wait network')
    if not admin_debug:
        time.sleep(30)

    logger.info('to check network')
    network_status = check_network()
    # network_status = 1
    # logger.info(' check network end')

    if network_status:
        # 网络 ok 先对时
        # logger.info('network is ok')

        logger.info('network is ok')

        now_timestamp = time.time()
        now_timestamp = round(now_timestamp)
        pass
    else:
        logger.info('network is not ok')

    odoo = get_odoo(conf_file, gatewate_code)
    if odoo.session_id:
        logger.info('odoo connect ok')

    # 给 控制模块, 设置 odoo
    ctrl.odoo = odoo

    # 将本地缓存的数据 写入服务器
    ctrl.sensor_loc_to_odoo()

    # 以上 基础工作做完了

    # 5 下发 唤醒
    # ctrl.send_wakeup()

    # 5 下发 读设备
    ctrl.read_device()

    # time.sleep(1000)

    if not odoo.session_id:
        logger.info('sleep 60s wait network')
        time.sleep(100)

        logger.info('to check network')
        network_status = check_network(50)
        if network_status:
            logger.info('to check network')
            now_timestamp = time.time()
            now_timestamp = round(now_timestamp)
            odoo = get_odoo(conf_file, gatewate_code)
        else:
            logger.info('network is not ok')

    if odoo.session_id:
        logger.info('odoo connect ok')
        # 给 控制模块, 设置 odoo
        ctrl.odoo = odoo
        # 将本地缓存的数据 写入服务器
        logger.info('send data to server....')
        ctrl.sensor_loc_to_odoo()
        logger.info('send data to server ok')
    else:
        logger.info('network is not ok')

    # 6 下发关机命令
    upload_log(gatewate_code)

    shutdown = ctrl.shutdown_me(now_timestamp)

    # 7 退出程序
    if not shutdown:
        logger.debug('not ack, I am not shutdown')
        upload_log(gatewate_code)
        return

    logger.info('I am shutdown')

    # 关机
    if admin_debug:

        return

    # 关机
    sudo_password = "root"
    command = "sudo shutdown -h now"
    os.system('echo %s | sudo -S %s' % (sudo_password, command))

    return

    # 正式程序的流程:
    # 1
    # 连接 server
    # 连接 local db
    # 处理 本地缓存

    # 每次启动后 从服务器 获取, 刷新 名下 node 列表
    # 这个 列表 需要 通知 给 下位机

    # 启动后  先处理串口, 不用管 odoo
    # 串口处理后, 再 等待 odoo ok  写 odoo

    # 2
    # 启动计时器 10秒
    # 给串口发送 测试指令, 等待串口
    # 测试指令的应答 与定时器 的顺序 哪个先到
    # 若超时, 重复三次呼叫
    # 若三次呼叫 都无应答, 则判断 从机故障. 上报服务器 网关的控制板故障. 本机 关机.
    # 本机关机后, 再也没有启动. 则 server 端 有超时判断, 记录 网关失联故障
    # 测试指令有应答, 串口 ok

    # 3
    # 访问服务器 获取

    # password = "123456"
    # command = "sudo cat /etc/hostname"

    # print("\ncheng.")
    # print(os.system("ping -c 4 www.baidu.com"))
    # print("\nyong.")
    # print(os.system("ping -c 4 www.taobao.com"))
    # print("\nqiang.")

    # os.system('echo %s | sudo -S %s' % (password, command))


def main():
    # main_base()

    try:
        main_base()

    except Exception as e:
        logger.error('Error: %s' % e)
        logger.error('Error: %s' % str(e))
        print('Error: %s' % str(e))
